package cn.dai.servlet;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 这个路径可以从数据库获取到
        String filePath = "C:\\Users\\Administrator\\IdeaProjects\\JavaWeb\\out\\artifacts\\FileUpload_war_exploded\\repo\\20200605175841.jpg";

        // 得到我们的文件名称
        String file = filePath.substring(filePath.lastIndexOf("\\") + 1);

        // 读取进内存，封装为流对象
        InputStream inputStream = new FileInputStream(filePath);

        // 获取MIME类型
        String mimeType = request.getServletContext().getMimeType(file);

        // 设置响应
        response.setContentType(mimeType);
        response.setHeader("Content-Disposition","attachment;filename="+file);

        // 返回字节大小
        int copy = IOUtils.copy(inputStream, response.getOutputStream());
        System.out.println(copy);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp){

    }
}
